let fs=  require('fs'); // node10+ 开始支持 require('fs').promises
let Promise1 = require('./promise');

function isPromise(value){
    if((typeof value === 'object' && value!==null)  || typeof value =='function'){
        if(typeof value.then === 'function'){
            return true;
        }
    }
    return false
}


//--- race
Promise.race = function (values) {
    return new Promise((resolve, reject) => {
        for (let i = 0; i < values.length; ++i) {
            let current = values[i];
            if (isPromise(current)) {
                current.then(resolve, reject);
            } else {
                resolve(current); //resolve，reject反复调用都只会在第一次时有效 so不用担心循环会反复调用resolve、reject
            }
        }
    });
};

Promise.race([read('./name.txt','utf8'),read('./age.txt','utf8'),1,2]).then(data=>{
    console.log(data);
}).catch(err=>{
    console.log(err);
})


//--- all

Promise.all = function(promises){
    return new Promise((resolve,reject)=>{
        let arr = [];
        let index = 0;
        let processData = function (i, y) {
            arr[i] = y;
            if (++index === promises.length) {
                resolve(arr);
            }
        };
        for(let i =0 ; i< promises.length;i++){
            let value =promises[i];
            if(isPromise(value)){
                value.then(function(y){
                    // i 对应的结果 就是 y
                    processData(i,y);
                },reject)
            }else{
                processData(i,value); //如果不是promise就直接放进去
            }
        }
    });
}

// 都成功才算成功 有一个失败就算失败
Promise.all([read('./name.txt','utf8'),read('./age.txt','utf8'),1,2]).then(data=>{
    console.log(data); //['ahhh','age',1,2] 顺序就是all里数组参数接受数组成员的顺序
}).catch(err=>{
    console.log(err);
})

function read(filename,encoding){
    let dfd = Promise1.defer();
    fs.readFile(filename,encoding,(err,data)=>{
        if(err){
            dfd.reject(err)
        }else{
            dfd.resolve(data);
        }
    })
    return  dfd.promise;
}

